var express = require('express');
var Invoice = require('../modules/invoice')
var router = express.Router();

// 添加
router.post('/', function (req, res) {
  var { people, day, dep, user, name, domains } = req.body;
  console.log(req.body);
  var invoice = new Invoice({ people, day, dep, user, name, domains})
  invoice.save(function (err) {
    if (err) {
      res.json({
        success: false,
        message: "录入失败！"
      })
    }
  })
  res.json({ success: true, message: "录入成功！" })
})

// 查看
router.get('/', function (req, res) {
  Invoice.find({}, function (err, categories) {
    res.json({
      success: true,
      data: categories
    })
  })
})

// 更新
router.put('/', function (req, res) {

  // 解构赋值
  var { title, newTitle } = req.body;
  Invoice.findOneAndUpdate({ title: title }, { title: newTitle }, function (err, invoice) {
    if (err) {
      res.json({
        success: false, message: "更新失败"
      })
    }
  })
  res.json({ success: true, message: "更新成功！" })
})

// 删除
router.delete('/', function (req, res) {
  console.log('delete invoice');

  // 解构赋值
  var { title } = req.body;

  Invoice.remove({ title: title }, function (err) {
    if (err) {
      res.json({
        success: false, messge: "删除失败！"
      })
    }
  })
  res.json({ success: true, message: "删除成功！" })
})

module.exports = router;